package com.example.demo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.demo.common.Result;
import com.example.demo.entity.News;
import com.example.demo.service.NewsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Resource
    NewsService newsService;

    /**
     * 分页查询书籍
     * @param pageNum
     * @param pageSize
     * @param title
     * @param author
     * @return
     */
    @GetMapping("/selectNews")
    public Result<?> selectPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                @RequestParam(defaultValue = "10") Integer pageSize,
                                @RequestParam(defaultValue = "") String title,
                                @RequestParam(defaultValue = "") String author){
        IPage<News> NewsPage = newsService.selectPage(pageNum,pageSize,title,author);
        return Result.success(NewsPage);
    }

    /**
     * 新增书籍
     * @param news
     * @return
     */
    @PostMapping("/addNews")
    public Result<?> save(@RequestBody News news){
        if (news.getTitle() == null || news.getAuthor() == null || news.getContent() == null){
            return Result.error("4001","所填字段不能为空,新增失败！");
        }
        newsService.addNews(news);
        return Result.success();
    }

    /**
     * 更新书籍信息
     * @param news
     * @return
     */
    @PutMapping("/updateNews")
    public Result<?> update(@RequestBody News news){
        if (news.getTitle() == null || news.getAuthor() == null || news.getContent() == null){
            return Result.error("4001","所填字段不能为空,更新失败！");
        }
        newsService.updateNews(news);
        return Result.success();
    }

    /**
     * 删除书籍
     * @param newsId
     * @return
     */
    @GetMapping("/deleteNews")
    public Result<?> delete(@RequestParam int newsId){
        newsService.deleteNews(newsId);
        return  Result.success();
    }
}
